import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectEntityManager } from '@nestjs/typeorm';
import { EntityManager } from 'typeorm';
import { Visit } from './entities/visit.entity';

@Injectable()
export class VisitService {
  @InjectEntityManager()
  private manage: EntityManager;

  createVisit(createVisitDto: any) {
    const visit = new Visit();
    visit.ip = createVisitDto.ip;
    visit.userId = createVisitDto.userId || null;
    visit.username = createVisitDto.username || null;
    if(createVisitDto.url.indexOf('/apis/getOpenAi/') > -1) {
      visit.url = '/apis/getOpenAi/';
    } else {
      const url = createVisitDto.url.split('?')[0];
      visit.url = decodeURI(url).substring(0, 225);
    }
    visit.userAgent = createVisitDto.userAgent;
    visit.origin = createVisitDto.origin;
    try {
      this.manage.save(Visit, visit);
    } catch (error) {
      throw new HttpException(error, HttpStatus.BAD_REQUEST);
    }
  }

  async visitCount() {
    const total = await this.manage.count(Visit)
    return total
  }

  async visitList() {
    const result = await this.manage.find(Visit, {
      order: {
        createDate: 'DESC'
      },
      take: 100
    })
    return result
  }
}
